//
//  SNSettingViewController.m
//  project
//
//  Created by 黄建华 on 2017/11/20.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNSettingViewController.h"
#import "SNInfoView.h"
#import "SNPersonSetViewController.h"
#import  "FeedBackViewController.h"
@interface SNSettingViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>
@property(nonatomic, strong) UIImageView  *backImageView;
@property(nonatomic, strong) UIView       *backView;
@property(nonatomic, strong) SNInfoView   *firstView;
@property(nonatomic, strong) SNInfoView   *secondView;
@property(nonatomic, strong) SNInfoView   *thirdView;
@property(nonatomic, strong) SNInfoView   *forthView;
@property(nonatomic, strong) UITableView  *tableView;
@property(nonatomic, strong) NSArray      *dataSource;
@property(nonatomic, strong) UIButton     *headImageBtn;
@property(nonatomic, strong) UILabel      *nameLabel;
@property(nonatomic, strong) UILabel      *weightLabel;
@property(nonatomic, strong) UILabel      *dateLabel;
@property(nonatomic, strong) UILabel      *BMILabel;
@property(nonatomic, strong) UILabel      *userIDLabel;
@property(nonatomic, assign) BOOL         selected;
@property (nonatomic, strong) UIImageView *animateView;
@property (nonatomic, strong) UIView      *bgView;
@end

@implementation SNSettingViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (SN_USER.portrait.length > 0) {
        _headImageBtn.image = SN_USER.headImage;
    } else {
        _headImageBtn.image = [UIImage imageNamed:@"loginhead"];
    }
    _nameLabel.text   = SN_USER.nickName;
    _weightLabel.text = SN_USER.weightunitSet ? [NSString stringWithFormat:@"%.1flb", SN_USER.weight*2.2] : [NSString stringWithFormat:@"%.1fkg", SN_USER.weight];
    if ([SN_USER.weightTime isEqualToString:@"0000-00-00"]) {
        _dateLabel.text = SN_Text(@"暂无数据");
    }else{
        _dateLabel.text   = [NSString stringWithFormat:@"%@", SN_USER.weightTime];
    }
    _BMILabel.text    = [NSString stringWithFormat:@"%@", SN_USER.BMI];
    [SportModel getMaxDayStep];
    [SportModel getmaxContinueDays];
    [SportModel getMaxWeekStep];
    [SportModel getMaxMonthStep];
    [self updateUI];
    
    NSInteger width = 0;
    if (KK_ShareData.lastVcTag > KK_ShareData.currentVCTag) {
        width = HHHWIDTH;
    }
    if (KK_ShareData.lastVcTag < KK_ShareData.currentVCTag) {
        width = -HHHWIDTH;
    }
    
    if (KK_ShareData.lastVcTag == KK_ShareData.currentVCTag) {
        width = 0;
    }
    if (width != 0) {
        if (_bgView) {
            [_bgView removeFromSuperview];
            _bgView = nil;
        }
        if (_animateView) {
            [_animateView removeFromSuperview];
            _animateView = nil;
        }
        
        _animateView = [[UIImageView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_animateView];
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(HHHWIDTH, HHHHEIGHT), NO, 0.0);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        _animateView.image = viewImage;
        
        _bgView                 = [[UIView alloc] initWithFrame:self.view.frame];
        _bgView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_bgView];
        [self.view bringSubviewToFront:_animateView];
        _animateView.frame  = SNFRAME(width, 0, HHHWIDTH, HHHHEIGHT);
        _animateView.hidden = NO;
        _bgView.hidden      = NO;
        [UIView animateWithDuration:VIEWANIMATETIME animations:^{
            _animateView.frame = SNFRAME(0, 0, HHHWIDTH, HHHHEIGHT);
        } completion:^(BOOL finished) {
            _animateView.hidden = YES;
            _bgView.hidden = YES;
        }];
    }
}

- (void)updateUI {
    _firstView.contentStr = [NSString stringWithFormat:@"%ld %@", (long)SN_USER.max_step, SN_Text(@"步")];
    _firstView.dateStr    = SN_USER.max_step_date;
    
    _secondView.contentStr = [NSString stringWithFormat:@"%ld %@", (long)SN_USER.max_reach_times, SN_Text(@"天")];
    if (SN_USER.max_reach_times > 0) {
        _secondView.dateStr = [NSString stringWithFormat:@"%@～%@", [SN_USER.max_reach_start substringFromIndex:5], [SN_USER.max_reach_end substringFromIndex:5]];
    }
    
    _thirdView.contentStr = [NSString stringWithFormat:@"%ld %@", (long)SN_USER.max_week_step, SN_Text(@"步")];
    if (SN_USER.max_week_step > 0) {
        _thirdView.dateStr = [NSString stringWithFormat:@"%@～%@", [SN_USER.max_week_start substringFromIndex:5], [SN_USER.max_week_end substringFromIndex:5]];
    }
    
    _forthView.contentStr = [NSString stringWithFormat:@"%ld %@", (long)SN_USER.max_month_step, SN_Text(@"步")];
    if (SN_USER.max_month_step > 0) {
        _forthView.dateStr = [NSString stringWithFormat:@"%@", SN_USER.max_month];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addHeadView];
    [self addInfoView];
    [self addTableView];
}

- (void)addHeadView {
    UIImage *backImage = UIImageNamed(@"背景");
    
    _backImageView                        = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), HHHWIDTH, HHHWIDTH*backImage.size.height/backImage.size.width)];
    _backImageView.userInteractionEnabled = YES;
    _backImageView.image                  = backImage;
    [self.view addSubview:_backImageView];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setImage:[UIImage imageWithImageName:@"分享share"] forState:UIControlStateNormal];
    [shareBtn setTintColor:[UIColor whiteColor]];
    shareBtn.frame = CGRectMake(HHHWIDTH -44 -10, 20+FitSimpleIpx(0, 20), 44, 44);
    [shareBtn addTouchUpTarget:self action:@selector(shareBtnClick)];
    [self.view addSubview:shareBtn];
    
    _headImageBtn                    = [UIButton buttonWithType:UIButtonTypeCustom];
    _headImageBtn.frame              = CGRectMake(HHHWIDTH/12, HHHWIDTH/5, HHHWIDTH/3, HHHWIDTH/3);
    _headImageBtn.layer.cornerRadius = HHHWIDTH/6;
    _headImageBtn.clipsToBounds      = YES;
    _headImageBtn.layer.borderColor  = SNCOLORWHITE.CGColor;
    _headImageBtn.layer.borderWidth  = 1;
    [self.view addSubview:_headImageBtn];
    
    CGFloat labelHeight = (_headImageBtn.width-FitH(20))/5;
    CGFloat width = FitSimpleSize(-22, -22, 0, 0, 0);
    CGFloat font = FitSimpleSize(10.0, 11.0, 13.0, 13.0, 13.0);
    _nameLabel           = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2 +width, HHHWIDTH/5, HHHWIDTH/2, labelHeight)];
    _nameLabel.textColor = SNCOLORWHITE;
    _nameLabel.font      = SNFONTMIN(14);
    [self.view addSubview:_nameLabel];
    
    NSArray *arr = @[@"ID：", @"上次测量体重：", @"上次测量日期：", @"BMI指数："];
    for (int i = 0; i < 4; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH/2 +width, _nameLabel.bottom+FitH(5)+(FitH(5)+labelHeight)*i, HHHWIDTH/2, labelHeight)];
        label.text          = SN_Text(arr[i]);
        label.textColor     = UIColorHEX(0x838485);
        label.font          = SNFONTMIN(font);
        label.textAlignment = NSTextAlignmentLeft;
        CGSize titleSize = [label.text sizeWithFont:label.font maxSize:CGSizeMake(MAXFLOAT, labelHeight)];
        label.size = CGSizeMake(titleSize.width, labelHeight);
        [self.view addSubview:label];
        if (i == 0) {
            _userIDLabel           = [[UILabel alloc]initWithFrame:CGRectMake(label.right, _nameLabel.bottom+FitH(5), HHHWIDTH-label.right, labelHeight)];
            _userIDLabel.textColor = SNCOLORWHITE;
            _userIDLabel.font      = SNFONTMIN(font);
            _userIDLabel.text      = [NSString stringWithFormat:@"%@", SN_USER.user_id];
            [self.view addSubview:_userIDLabel];
        } else if (i == 1) {
            _weightLabel           = [[UILabel alloc]initWithFrame:CGRectMake(label.right, _userIDLabel.bottom+FitH(5), HHHWIDTH-label.right, labelHeight)];
            _weightLabel.textColor = SNCOLORWHITE;
            _weightLabel.font      = SNFONTMIN(font);
            [self.view addSubview:_weightLabel];
        } else if (i == 2) {
            _dateLabel           = [[UILabel alloc]initWithFrame:CGRectMake(label.right, _weightLabel.bottom+FitH(5), HHHWIDTH-label.right, labelHeight)];
            _dateLabel.textColor = SNCOLORWHITE;
            _dateLabel.font      = SNFONTMIN(font);
            [self.view addSubview:_dateLabel];
        } else {
            _BMILabel           = [[UILabel alloc]initWithFrame:CGRectMake(label.right, _dateLabel.bottom+FitH(5), HHHWIDTH-label.right, labelHeight)];
            _BMILabel.textColor = SNCOLORWHITE;
            _BMILabel.font      = SNFONTMIN(font);
            [self.view addSubview:_BMILabel];
        }
    }
}

- (void)addInfoView {
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, _backImageView.bottom, HHHWIDTH, FitH(260))];
    
    _firstView = [[SNInfoView alloc]initWithFrame:CGRectMake(FitW(25), FitH(30), HHHWIDTH/2-FitW(25), FitH(120)) withType:0];
    
    [_backView addSubview:_firstView];
    
    _secondView = [[SNInfoView alloc]initWithFrame:CGRectMake(HHHWIDTH/2+FitW(25), FitH(30), HHHWIDTH/2-FitW(25), FitH(120)) withType:1];
    
    [_backView addSubview:_secondView];
    
    _thirdView = [[SNInfoView alloc]initWithFrame:CGRectMake(FitW(25), _firstView.bottom, HHHWIDTH/2-FitW(25), FitH(120)) withType:2];
    
    [_backView addSubview:_thirdView];
    
    _forthView = [[SNInfoView alloc]initWithFrame:CGRectMake(HHHWIDTH/2+FitW(25), _firstView.bottom, HHHWIDTH/2-FitW(25), FitH(120)) withType:3];
    
    [_backView addSubview:_forthView];
    [self updateUI];
    UILabel *line = [[UILabel alloc]initWithFrame:CGRectMake(0, _backView.bottom-1, HHHWIDTH, 1)];
    line.backgroundColor = SNCOLORSEPRATE;
    [_backView addSubview:line];
}

- (void)addTableView {
    _dataSource                             = @[HHH_Text(@"个人设置1"),HHH_Text(@"退出当前登录账号")];
    _tableView                              = [[UITableView alloc]initWithFrame:CGRectMake(0, _backImageView.bottom, HHHWIDTH, HHHHEIGHT-_backImageView.bottom-49) style:UITableViewStylePlain];
    _tableView.delegate                     = self;
    _tableView.dataSource                   = self;
    _tableView.separatorStyle               = UITableViewCellSeparatorStyleNone;
    _tableView.tableHeaderView              = _backView;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = _dataSource[indexPath.row];
    cell.textLabel.font = SNFONT(16);
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [imageView setImage:UIImageNamed(@"进入(1)")];
    cell.accessoryView = imageView;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selected == NO) {
        self.selected = YES;
        if (indexPath.row == 0) {
            SNPersonSetViewController *personVC = [[SNPersonSetViewController alloc]init];
            personVC.type = 1;
            CustomTabBar *tabBar = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:personVC animated:YES];
        }
//        else if (indexPath.row == 1) {
//            FeedBackViewController *feedVC = [[FeedBackViewController alloc]init];
//            [self.navigationController pushViewController:feedVC animated:YES];
//        }
        else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:SN_Text(@"是否确定？")
                                                            message:SN_Text(@"退出当前账户/游客登录模式后，您的设备蓝牙将断开，是否要继续") delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:SN_Text(@"取消"), SN_Text(@"确定"), nil];
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            [alert show];
        }
        self.selected = NO;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        //清楚当前设备信息
        [KK_BLEConfig updateService:0];
        [KK_BLELastDevice setObjectValue:@""];
        [KK_BLELastDeviceMac setObjectValue:@""];
        [KK_BLEConnect initiativeDismiss];
        [HASLOGIN setBOOLValue:NO];
        [kK_App enterLoginVc];
    }
}

- (void)shareBtnClick {
    UIGraphicsBeginImageContext(CGSizeMake(screenWidth, screenHeight));
    
    [[UIApplication sharedApplication].delegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSMutableArray *items = [[NSMutableArray alloc] init];
    [items addObject:image];
    
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    NSMutableArray           *excludedActivityTypes  = [NSMutableArray arrayWithArray:@[
                                                                                        UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo, UIActivityTypeAirDrop,
                                                                                        UIActivityTypeOpenInIBooks]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray *__nullable returnedItems, NSError *__nullable activityError){
    };
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

